
import paramiko


class op_ssh_config:
    def __init__(self):
        self.hostname = "192.168.1.101"
        self.username = "ubuntu"
        self.password = "123456"
op_ssh_config = op_ssh_config()

def execute_remote_command(command, hostname = op_ssh_config.hostname, username = op_ssh_config.username, password = op_ssh_config.password): 
    # 创建 SSH 客户端
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    try:
        # 连接远程主机
        client.connect(hostname=hostname, username=username, password=password, banner_timeout=360, timeout=360,
                       auth_timeout=360)
        stdin, stdout, stderr = client.exec_command(command)

        # 输出命令执行结果
        result = stdout.read().decode().strip()
        error = stderr.read().decode().strip()

        return result, error

    finally:
        # 关闭 SSH 连接
        client.close()

def run_remote_script( path, hostname = op_ssh_config.hostname, username = op_ssh_config.username, password = op_ssh_config.password):
    # 创建SSH客户端
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    # 连接到远程主机
    client.connect(hostname=hostname, username=username, password=password)

    # 执行shell命令
    stdin, stdout, stderr = client.exec_command(path)
    print('错误检测:')
    print(stderr.read().decode())
    client.close()

def upload_file(local_path, hostname = op_ssh_config.hostname, username = op_ssh_config.username, password = op_ssh_config.password):
    # 创建 SSH 客户端
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    try:
        # 连接远程主机
        client.connect(hostname=hostname, username=username, password=password, banner_timeout=360, timeout=360,
                       auth_timeout=360)

        # 上传文件
        sftp = client.open_sftp()
        sftp.put(local_path, remote_path)

    finally:
        # 关闭 SSH 连接
        client.close()

def download_file(remote_path,  hostname = op_ssh_config.hostname, username = op_ssh_config.username, password = op_ssh_config.password):
    # 创建 SSH 客户端
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    try:
        # 连接远程主机
        client.connect(hostname=hostname, username=username, password=password, banner_timeout=360, timeout=360,
                       auth_timeout=360)

        # 下载文件
        sftp = client.open_sftp()
        sftp.get(remote_path, local_path)

    finally:
        # 关闭 SSH 连接
        client.close()


def test():
    # 执行远程命令
    result, error = execute_remote_command("ls -l")
    print(result)
    print(error)

    # 执行远程脚本
    run_remote_script("test.sh")

    # 上传文件
    upload_file("test.sh", "/tmp/test.sh")

    # 下载文件
    download_file("/tmp/test.sh", "test.sh")